<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #materialSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择母件料品料号" :disabled="isDetail" readonly @search="openMaterial" />
      </template>
      <!-- <template #unitSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择单位" :disabled="isDetail" readonly @search="openUnit" />
      </template> -->
      <template #organizationSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择组织" :disabled="isDetail" readonly @search="openOrganization" />
      </template>          
      <template #warehouse="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择仓库" :disabled="isDetail" readonly  @search="openWarehouse"  />
      </template>          
      <!-- <template #organizationSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择组织" :disabled="isDetail" readonly  @search="openWarehouse"  />
      </template> -->
    </BasicForm>    
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="子件内容" key="basMaterialBomChild" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="basMaterialBomChild"
          :loading="basMaterialBomChildTable.loading"
          :columns="basMaterialBomChildTable.columns"
          :dataSource="basMaterialBomChildTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #action="props">
            <a-input-search @search="handleView(props, 1)" placeholder="请选择料品" :disabled="isDetail" readonly v-model:value="props.row.materialCode" />
          </template>
          <template #childSlot="props">
            <a-input-search @search="handleChildView(props, 1)" placeholder="请选择" :disabled="isDetail" readonly v-model:value="props.row.childName" />
          </template>
          <!-- <template #unitSlot="props">
            <a-input-search @search="handleUnitView(props, 1)" placeholder="请选择单位" readonly v-model:value="props.row.unitName" />
          </template> -->
        </JVxeTable>
      </a-tab-pane>
      <a-tab-pane tab="加工工艺" key="basMaterialBomTechnology" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="basMaterialBomTechnology"
          :loading="basMaterialBomTechnologyTable.loading"
          :columns="basMaterialBomTechnologyTable.columns"
          :dataSource="basMaterialBomTechnologyTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #operationSlot="props">
            <a-input-search @search="handleOperationView(props, 1)" placeholder="请选择工艺" :disabled="isDetail" readonly v-model:value="props.row.processManagementName" />
          </template>
        </JVxeTable>
      </a-tab-pane>
      <a-tab-pane tab="替代关系" key="basMaterialBomReplace" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="basMaterialBomReplace"
          :loading="basMaterialBomReplaceTable.loading"
          :columns="basMaterialBomReplaceTable.columns"
          :dataSource="basMaterialBomReplaceTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #action="props">
            <a-input-search @search="handleView(props, 2)" placeholder="请选择料品" :disabled="isDetail" readonly v-model:value="props.row.materialName" />
          </template>
          <!-- <template #unitSlot="props">
            <a-input-search @search="handleUnitView(props, 2)" placeholder="请选择单位" :disabled="isDetail" readonly  v-model:value="props.row.unitName" />
          </template> -->
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 表单区域 -->
  <materialSelectModel @register="regModal" @getSelectResult="handleSuccess" v-bind="getBindValue"></materialSelectModel>
  <!-- 料品选择 -->
  <materialSelectModel @register="regMaterialModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue"></materialSelectModel>
  <!-- 单位 -->
  <unitSelectModel @register="unitRegModal" @getSelectResult="unithandleSuccess" v-bind="getBindValue"></unitSelectModel>
  <!-- 子表单位 -->
  <unitSelectModel @register="unitRegModals" @getSelectResult="unithandleSuccesss" v-bind="getBindValue"></unitSelectModel>
  <!-- 子表单位 -->
  <processManagementSelectModels
    @register="processManagementRegModals"
    @getSelectResult="processManagementhandleSuccesss"
    v-bind="getBindValue"
  ></processManagementSelectModels>
  <!-- 子表单位 -->
  <bomSelectModel @register="bomRegModals" @getSelectResult="bomhandleSuccesss" v-bind="getBindValue"></bomSelectModel>
  <!-- 组织 -->
  <organizationSelectModel @register="organizationRegModal" @getSelectResult="organizationHandleSuccess" v-bind="getBindValue"/>
  <!-- 仓库 -->
  <warehouseSelectModel @register="warehouseRegModal" @getSelectResult="warehouseHandleSuccess" v-bind="getBindValue" />
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, basMaterialBomChildColumns, basMaterialBomTechnologyColumns, basMaterialBomReplaceColumns } from '../BasMaterialBom.data';
import { saveOrUpdate, basMaterialBomChildList, basMaterialBomTechnologyList, basMaterialBomReplaceList } from '../BasMaterialBom.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import materialSelectModel from './materialSelectModel.vue';
import unitSelectModel from '/@/views/components/unitSelectModel.vue';
import processManagementSelectModels from '/@/views/components/processManagementSelectModels.vue';
import bomSelectModel from '/@/views/components/bomSelectModel.vue';
import organizationSelectModel from '/@/views/supplier/purchaseManager/busBuyingRequisition/components/organizationSelectModel.vue';
import warehouseSelectModel from '/@/views/components/warehouseSelectModel.vue';
  
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);
const formDisabled = ref(false);
const refKeys = ref(['basMaterialBomChild', 'basMaterialBomTechnology', 'basMaterialBomReplace']);
const activeKey = ref('basMaterialBomChild');
const basMaterialBomChild = ref();
const basMaterialBomTechnology = ref();
const basMaterialBomReplace = ref();
const tableRefs = { basMaterialBomChild, basMaterialBomTechnology, basMaterialBomReplace };
const basMaterialBomChildTable = reactive({
  loading: false,
  dataSource: [],
  columns: basMaterialBomChildColumns,
});
const basMaterialBomTechnologyTable = reactive({
  loading: false,
  dataSource: [],
  columns: basMaterialBomTechnologyColumns,
});
const basMaterialBomReplaceTable = reactive({
  loading: false,
  dataSource: [],
  columns: basMaterialBomReplaceColumns,
});
const [organizationRegModal, { openModal: openOrganizationModal }] = useModal();
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(basMaterialBomChildList, { id: data?.record?.id }, basMaterialBomChildTable);
    requestSubTableData(basMaterialBomTechnologyList, { id: data?.record?.id }, basMaterialBomTechnologyTable);
    requestSubTableData(basMaterialBomReplaceList, { id: data?.record?.id }, basMaterialBomReplaceTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => ( unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'basMaterialBomChild';
  basMaterialBomChildTable.dataSource = [];
  basMaterialBomTechnologyTable.dataSource = [];
  basMaterialBomReplaceTable.dataSource = [];
}
const [regModal, { openModal }] = useModal();
const [regMaterialModal, { openModal: openMaterialModal }] = useModal();
const [unitRegModal, { openModal: openUnitModal }] = useModal();
const [unitRegModals, { openModal: openUnitModals }] = useModal();
const [processManagementRegModals, { openModal: openProcessManagementModals }] = useModal();
const [bomRegModals, { openModal: openBomModals }] = useModal();
const [warehouseRegModal, { openModal: openStorageAndCompleteWarehouseModal }] = useModal();

//打开选择组织
function openOrganization() {
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

//组织回写
function organizationHandleSuccess(val) {
  setFieldsValue({
    supplyOrganizationId: val[0].value,
    supplyOrganizationName: val[0].label,
  });
}

function openMaterial() {
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

//打开单位选择
function openUnit(props) {
  openUnitModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
let index: number = 0;
function handleView(props, type) {
  console.log(props);
  
  index = props.params.seq - 1;
  openModal(true, {
    isUpdate: false,
    showFooter: true,
    type: type,
  });
}
function handleUnitView(props, type) {
  index = props.params.$rowIndex;
  openUnitModals(true, {
    isUpdate: false,
    showFooter: true,
    type: type,
  });
}
let materialId =ref<string>('')

function handleChildView(props, type) {
  materialId = props.row.materialId || '';
  index = props.params.$rowIndex;
  openBomModals(true, {
    isUpdate: false,
    showFooter: true,
    materialId:materialId
  });
}
function handleOperationView(props, type) {
  index = props.params.$rowIndex;
  openProcessManagementModals(true, {
    isUpdate: false,
    showFooter: true,
    type: type,
  });
}
function openWarehouse() {
  openStorageAndCompleteWarehouseModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

const getBindValue = Object.assign({}, '');

//选择回写
function handleSuccess(val, values, type) {
  console.log(val, values);
  if (type == 1) {
    basMaterialBomChildTable.dataSource = basMaterialBomChild.value!.getTableData();
    basMaterialBomChildTable.dataSource[index].materialName = val[0].label;
    basMaterialBomChildTable.dataSource[index].materialId = val[0].value;
    basMaterialBomChildTable.dataSource[index].materialCode = val[0].item.code;
    basMaterialBomChildTable.dataSource[index].unitId = val[0].item.stockUnitId;
    basMaterialBomChildTable.dataSource[index].unitName = val[0].item.stockUnitName;
    basMaterialBomChildTable.dataSource[index].warehouseId = val[0].item.warehouseId;
    basMaterialBomChildTable.dataSource[index].warehouseName = val[0].item.warehouseName;
  } else if (type == 2) {
    basMaterialBomReplaceTable.dataSource = basMaterialBomReplace.value!.getTableData();
    basMaterialBomReplaceTable.dataSource[index].materialName = val[0].label;
    basMaterialBomReplaceTable.dataSource[index].materialId = val[0].value;
    basMaterialBomReplaceTable.dataSource[index].materialCode = val[0].item.code;
    basMaterialBomReplaceTable.dataSource[index].unitId = val[0].item.stockUnitId;
    basMaterialBomReplaceTable.dataSource[index].unitName = val[0].item.stockUnitName;
    basMaterialBomChildTable.dataSource[index].warehouseId = val[0].item.warehouseId;
    basMaterialBomChildTable.dataSource[index].warehouseName = val[0].item.warehouseName;
  }
  materialId=val[0].item.id
}
//选择回写
function unithandleSuccesss(val, values, type) {
  if (type == 1) {
    basMaterialBomChildTable.dataSource = basMaterialBomChild.value!.getTableData();
    basMaterialBomChildTable.dataSource[index].unitName = val[0].label;
    basMaterialBomChildTable.dataSource[index].unitId = val[0].value;
  } else if (type == 2) {
    basMaterialBomReplaceTable.dataSource = basMaterialBomReplace.value!.getTableData();
    basMaterialBomReplaceTable.dataSource[index].unitName = val[0].label;
    basMaterialBomReplaceTable.dataSource[index].unitId = val[0].value;
  }
}
//选择回写
function processManagementhandleSuccesss(val, values, type) {
  console.log(val, values, type);
  basMaterialBomTechnologyTable.dataSource = basMaterialBomTechnology.value!.getTableData();
  basMaterialBomTechnologyTable.dataSource[index].processManagementName = val[0].label;
  basMaterialBomTechnologyTable.dataSource[index].processManagementId = val[0].value;
}
function materialhandleSuccess(val, values) {  
  console.log("valvalvalvalvalvalval",val);
  
  setFieldsValue({
    materialName: val[0].label,
    materialId: val[0].value,
    materialCode: val[0].labels,
    unitId:val[0].item.stockUnitId,
    unitName:val[0].item.stockUnitName,
    productDepartmentCode:val[0].item.productDepartmentCode,
    productDepartmentId:val[0].item.productDepartmentId,
    productDepartmentName:val[0].item.productDepartmentName,
    warehouseId: val[0].item.warehouseId,
    warehouseName: val[0].item.warehouseName
  });
}
function unithandleSuccess(val, values) {
  setFieldsValue({
    unitName: val[0].label,
    unitId: val[0].value,
  });
}
  // 入库仓库回写
  function warehouseHandleSuccess(val) {
      setFieldsValue({
        warehouseId: val[0].value,
        warehouseName: val[0].label
      })
  }

function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    basMaterialBomChildList: allValues.tablesValue[0].tableData,
    basMaterialBomTechnologyList: allValues.tablesValue[1].tableData,
    basMaterialBomReplaceList: allValues.tablesValue[2].tableData,
  };
}
function bomhandleSuccesss(val, values) {
  console.log(val,values)
  basMaterialBomChildTable.dataSource = basMaterialBomChild.value!.getTableData();
  basMaterialBomChildTable.dataSource[index].childName = val[0].label;
  basMaterialBomChildTable.dataSource[index].childId = val[0].value;
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>